import {ref} from 'vue'
import {data} from '@drag/store'
import {componentData} from '@drag/componentData'
/**
 * 获取当前组件的所有父级节点
 * @param comp 当前组件
 * @returns
 */
export function findParentNodes(comp:componentData|{guid:any,title:string}){
    return ref(find({nodeId:comp.guid,tree:data.value}))
}
type Options = {
    /**被查找节点id */
    nodeId:string|number,
    /**被查找数据 */
    tree:componentData[],
    /**所有父节点 */
    parents?:componentData[],
    /**是否返回当前节点【不传返回所有父节点】 */
    meNode?:boolean
}
/**
 * 查找节点
 * @param {Options} options 查找参数 
 * @returns 
 */
export function find<T extends boolean = false>({
    nodeId,
    tree,
    parents = [],
    meNode // 设置为可选参数，默认值为 false
}: Options & { meNode?: T }): T extends true ? componentData : componentData[] | undefined {
    for (const node of tree) {
        if (node.guid == nodeId) {
            return (meNode ? node : parents) as any; // 根据 meNode 的值返回不同的类型
        }
        if (node.props?.children?.length) {
            for (const child of node.props.children) {
                if (child.guid == nodeId) {
                    return ([...parents, node] as any); // 返回父节点数组
                }
                if (child.children?.length) {
                    let parent = [...parents, node];
                    if (node.props.children.length > 1) parent.push(child);
                    let result = find({ nodeId, tree: child.children, parents: parent, meNode });
                    if (result) return result; // 返回找到的结果
                }
            }
        }
    }
    return undefined as any;
}